﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;


namespace RadioThermostat.Common
{
    public class WebCommunicator
    {
        
        private object monitor = new object();
        //lock to synchronize requests to thermostat server.  Server is singly threaded.
        //thanks to the rediothermostat project for this class
        public string HttpGet(string url)
        {
            lock (monitor)
            {
               
                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
                WebResponse resp = req.GetResponse();
                StreamReader sr = new StreamReader(resp.GetResponseStream());
                string result = sr.ReadToEnd();
               
                return result;
            }
        }

        public string HttpPost(string url, string parameters)
        {
            lock (monitor)
            {
               
                byte[] bytes = Encoding.UTF8.GetBytes(parameters);

                WebRequest req = (WebRequest)WebRequest.Create(url);
                req.ContentType = "application/json; charset=utf-8";
                req.Method = "POST";
                req.ContentLength = bytes.Length;
                System.IO.Stream stream = req.GetRequestStream();
                stream.Write(bytes, 0, bytes.Length);
                string utf = UTF8Encoding.ASCII.GetString(bytes);
               
                stream.Close();
                WebResponse resp = req.GetResponse();
                StreamReader sr = new StreamReader(resp.GetResponseStream());
                string result = sr.ReadToEnd();
              
                return result;
            }            
        }
    }
}
